package com.hyt.it.ogt.kq.service.bm.den;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hyt.it.ogt.kq.common.config.ConfigManager;
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

/**
 * PDF模板工具
 * 
 * @author wt
 * @version 2019年9月30日 下午7:41:21
 */
public class PdfTemplateUtils {
	private static Logger logger = LoggerFactory.getLogger(PdfTemplateUtils.class);

	
	
	private PdfTemplateUtils() {
		super();
	}



	/**
	 * 利用模板生成pdf
	 * 
	 * @param studentList
	 * @param outPath
	 * @param request
	 * @param taskName
	 * @throws Exception
	 */
	public static void pdfOut(Map<String, String> datemap, String outPath, ConfigManager globalConfig) throws Exception {
		FileOutputStream out = null;
		try {
			String templatePath = "";
			String noImage = "";
			// 模板
			if (System.getProperties().getProperty("os.name").toLowerCase().startsWith("win")) {
				templatePath = globalConfig.getPdfWindowsPath();
				noImage = globalConfig.getNoImageWindow();
			} else {
				templatePath = globalConfig.getPdfLinuxPath();
				noImage = globalConfig.getNoImageLinux();
			}

			// 生成的新文件路径
			String newPDFPath = outPath;
			logger.info("## 生成的新文件路径 :{} ", newPDFPath); 
			PdfReader reader;
			BaseFont bf = null;
			if (System.getProperties().getProperty("os.name").toLowerCase().startsWith("win")) {
				bf = BaseFont.createFont("c://windows//fonts//simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
			} else {
				bf = BaseFont.createFont("/usr/share/fonts/simsun/simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
			}
			logger.info("## 文本 :{} ", bf.toString()); 
			out = new FileOutputStream(newPDFPath);// 输出流

			List<PdfReader> list = new ArrayList<>();
			reader = new PdfReader(templatePath);// 读取pdf模板
			logger.info("## reader模板{} : ", reader); 
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			PdfStamper stamper = new PdfStamper(reader, bos);
			AcroFields form = stamper.getAcroFields();

			// 获取头像照片
			String imgPath = null;
			if (datemap.get("imgPhoto") != null) {
				imgPath =datemap.get("imgPhoto");
			} else {
				imgPath = noImage; 
			}
			Map<String, String> imgmap = new HashMap<>();
			imgmap.put("img", imgPath);
			// 文字类的内容处理
			form.addSubstitutionFont(bf);
			for (Map.Entry<String, String> entry : datemap.entrySet()) {
				form.setField(entry.getKey(), entry.getValue());
			}
			// 图片类的内容处理
			for (Map.Entry<String, String> imgmapEntry : imgmap.entrySet()) {
				String value = imgmapEntry.getValue();
				String key = imgmapEntry.getKey();
				String imgpath = value;
				int pageNo = form.getFieldPositions(key).get(0).page;
				Rectangle signRect = form.getFieldPositions(key).get(0).position;
				float x = signRect.getLeft();
				float y = signRect.getBottom();
				// 根据路径读取图片
				Image image = Image.getInstance(imgpath);
				// 获取图片页面
				PdfContentByte under = stamper.getOverContent(pageNo);
				// 图片大小自适应
				image.scaleToFit(signRect.getWidth(), signRect.getHeight());
				// 添加图片
				image.setAbsolutePosition(x, y);
				under.addImage(image);
			}
			stamper.setFormFlattening(true);// 如果为false，生成的PDF文件可以编辑，如果为true，生成的PDF文件不可以编辑
			stamper.close();
			PdfReader pdfReader = new PdfReader(bos.toByteArray());
			list.add(pdfReader);
			// 合并成为一个pdf
			Document document = new Document();
			PdfCopy copy = new PdfCopy(document, out);
			document.open();
			for (int k = 0; k < list.size(); k++) {
				PdfReader pdfReader2 = list.get(k);
				document.newPage();
				copy.addDocument(pdfReader2);
			}
			copy.close();
		} catch (Exception e) {
			logger.error("## pdfOut error", e);
		} finally {
			if(null != out) {
				out.close();
			}
		}
		
	}

}